package com.earnings.okhttputils.utils.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.earnings.R;
import com.earnings.okhttputils.utils.OkHttp.OkHttpUtils;
import com.earnings.okhttputils.utils.OkHttp.utils.ToastUtils;
import com.earnings.okhttputils.utils.UrlConstant.Constant;
import com.earnings.okhttputils.utils.UrlConstant.HttpUrl;
import com.earnings.okhttputils.utils.bean.WeixinPayData;
import com.earnings.okhttputils.utils.https.HttpMap;
import com.earnings.okhttputils.utils.https.HttpObjectCallback;
import com.earnings.okhttputils.utils.ui.dialog.phoenix.keybottondialog.PswKeyBoardBottomDialog;
import com.earnings.okhttputils.utils.utils.CommonUtil;
import com.earnings.okhttputils.utils.utils.PayResult;
import com.earnings.okhttputils.utils.weixin.WeiXinTool;

import java.util.Map;


public abstract class PaymentDialog extends Dialog implements
        View.OnClickListener {
    private Activity act;
    private LinearLayout layout;
    private LinearLayout mView;
    private TextView paytypeText,balance;
    String url;
    private PaytypeDialog paytypeDialog;
     private String paytype,price,worktype,balancepsw,orderid,phone,aim_level,note;
   private  PswKeyBoardBottomDialog keyBoardBottomDialog;
    /**
     * 付款框
     * price:金额
     * title:标题
     * type:业务类型 Contant.
     * @param context
     */
    public PaymentDialog(Context context, String price, String title,String type) {
        super( context, R.style.dialog_msg );
        this.act = (Activity) context;
        this.price = price;
        this.worktype = type;
        paytype=Constant.PAY_TYPE_BLANANCE;
        mView = (LinearLayout) act.getLayoutInflater().inflate( R.layout.dialog_payment,
                null );
        layout = (LinearLayout) mView.findViewById( R.id.cont );
        layout.getLayoutParams().width = act.getWindowManager()
                .getDefaultDisplay().getWidth();

        requestWindowFeature( Window.FEATURE_NO_TITLE );
        mView.findViewById( R.id.paytypeView ).setOnClickListener( this );
        mView.findViewById( R.id.sumbit ).setOnClickListener( this );
        balance= (TextView) mView.findViewById( R.id.balance );
        mView.findViewById( R.id.back ).setOnClickListener( this );
        paytypeText = (TextView) mView.findViewById( R.id.paytype );
        ((TextView) mView.findViewById( R.id.details )).setText( title );
        ((TextView) mView.findViewById( R.id.price )).setText( "￥" + price );

        //初始化选择支付方式
        paytypeDialog = new PaytypeDialog( act ) {
            @Override
            public void chooseItem(String typeid, String typename) {
                paytype = typeid;
                paytypeText.setText( typename );
                initBalance();
            }
        };
        initBalance();
        // setCanceledOnTouchOutside(false);
        // setCancelable(false);
        // init();
    }

    public void initBalance(){
        if(price.equals( "" ))return;
        if(paytype.equals( Constant.PAY_TYPE_BLANANCE )){
            balance.setVisibility( View.VISIBLE );

            float userBalance=Float.parseFloat( CommonUtil.getUser().getUser_money() );
            if(userBalance<Float.parseFloat(price)){
                balance.setText( "余额不足，请更换支付方式" );
                balance.setTextColor( act.getResources().getColor( R.color.textred ) );
            }else {
                balance.setText( "余额："+ CommonUtil.getUser().getUser_money()+"元");
                balance.setTextColor( act.getResources().getColor( R.color.textmiddle ) );
            }
        }else{
            balance.setVisibility( View.GONE );
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        // setContentView(layout);
        this.setCancelable( true );// 可以用“返回键”取消
        Window window = this.getWindow();
        window.setContentView( mView );
        window.setGravity( Gravity.BOTTOM ); // 此处可以设置dialog显示的位置
        window.setWindowAnimations( R.style.dialog_bottom_anim );
        WindowManager m = act.getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p =getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = (int) (d.getHeight() * 0.5);   //高度设置为屏幕的0.5
        getWindow().setAttributes(p);     //设置生效
    }

    @Override
    public void dismiss() {
        // TODO 自动生成的方法存根
        super.dismiss();
        // TextView tv=(TextView) act.findViewById(R.id.province);
        // tv.setText(province);
    }

    public void showTreasurepay(){
         paytypeDialog.showTreasurepay();
    }
    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.paytypeView) {
            paytypeDialog.show();

        } else if (i == R.id.back) {
            dismiss();

        } else if (i == R.id.sumbit) {
            if (paytype.equals(Constant.PAY_TYPE_WEIXIN) || paytype.equals( Constant.PAY_TYPE_ALIPAY)) {

                createOrderPay();
            } else {
                sumbit();
            }


        }
    }
    public void sumbit(){
        keyBoardBottomDialog=new PswKeyBoardBottomDialog(act,price);
        keyBoardBottomDialog.setOnPswKeyBoardResultListener(new PswKeyBoardBottomDialog.OnPswKeyBoardResultListener() {
            @Override
            public void getPswResult(String mResult) {
                balancepsw=mResult;
                createOrderPay();
                //onSumbit( mResult );
            }
        });
        keyBoardBottomDialog.show();
        dismiss();
    }
    public void setOrderid(String orderid){
        this.orderid=orderid;
    }
    public void setPaytype(String paytype){
        this.paytype=paytype;
    }
    public void setPhone(String phone){
        this.phone=phone;
    }
    public void setAimLevel(String aimlevel){
        this.aim_level=aimlevel;
    }
     public void setNote(String note){
          this.note=note;
     }

    public void cencelBanlance() {
        paytype=Constant.PAY_TYPE_WEIXIN;
        paytypeText.setText("微信支付");
        paytypeDialog.cencelBanlance();
    }

    public abstract void onSumbit(String type);


    private final int SDK_PAY_FLAG=1;
    public void alipay(final String orderInfo ){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(act);
                String result = alipay.pay(orderInfo.replace( "\\","" ), true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    public void wexin(WeixinPayData weixin) {
        WeiXinTool tool = new WeiXinTool(act );

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction( "weixin" );
        act.registerReceiver( new WeixinBroadcastReceiver(), intentFilter );
        tool.pay( weixin );
    }
    class WeixinBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int i = intent.getIntExtra("errCode", -1);
            switch (i) {
                case 0:
                    ToastUtils.showToast(act, "支付成功" );
                    onSumbit(paytype);
                    break;
                case -1:
                    break;
                case -2:

                    break;
            }

            context.unregisterReceiver(this);
        }
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult( (String) msg.obj );
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals( resultStatus, "9000" )) {
                        ToastUtils.showToast(act, "支付成功" );
                        onSumbit(paytype);
                    } else {
                       // skip( StatusPriceActivity.class );
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals( resultStatus, "8000" )) {
                            ToastUtils.showToast(act, "支付结果确认中" );
                        } else {
                            ToastUtils.showToast(act,  "支付失败" );

                        }
                    }
                    break;
                }
            }
        }
        ;
    };

    public void createOrderPay() {
final ProgressDialog prgessDialog=new ProgressDialog( act );
        prgessDialog.setText( "获取信息" );
        prgessDialog.show();

        Map map = new HttpMap(getContext());
        map.put( "money", price );
        map.put( "biz_type", worktype);
        map.put( "pay_code", paytype );
        if(worktype.equals(Constant.PAY_TYPE_WROK_OIL))
        map.put( "order_sn", orderid );
        if(paytype.equals(Constant.PAY_TYPE_BLANANCE)||paytype.equals(Constant.PAY_TYPE_CAIBAO))
        map.put( "paypwd",balancepsw );
        if(worktype.equals(Constant.PAY_TYPE_WROK_TRANSFER)){
            map.put( "payee_mobile", phone );
             map.put( "note", note );
        }
        if(worktype.equals(Constant.PAY_TYPE_WROK_UPGRADE))
            map.put( "aim_level", aim_level );
        if(worktype.equals(Constant.PAY_TYPE_WROK_RED))
            map.put( "order_sn", orderid );
        if(worktype.equals(Constant.PAY_TYPE_WROK_SHOP))
            map.put( "master_order_sn", orderid );
        if(paytype.equals( Constant.PAY_TYPE_WEIXIN )){
            OkHttpUtils.post().url( HttpUrl.USER_RECHARGE_ONLINE ).params( map ).build().execute(new HttpObjectCallback<WeixinPayData>(  getContext()) {
                @Override
                public void onSuccess(WeixinPayData object, String msg) {

                        wexin(object);

                    dismiss();
                    prgessDialog.dismiss();
                }
                @Override
                public void onFail(int code, String msg) {

                    ToastUtils.showToast(act,msg );

                    prgessDialog.dismiss();
                }


            } );
        }else{
        OkHttpUtils.post().url( HttpUrl.USER_RECHARGE_ONLINE ).params( map ).build().execute(new HttpObjectCallback<String>(  getContext()) {
            @Override
            public void onSuccess(String object, String msg) {

                if(paytype.equals(Constant.PAY_TYPE_ALIPAY))
                alipay(object);
                else if(paytype.equals(Constant.PAY_TYPE_BLANANCE)||paytype.equals(Constant.PAY_TYPE_CAIBAO)) {
                    keyBoardBottomDialog.showSus();
                    onSumbit(paytype);
                }
               dismiss();
                prgessDialog.dismiss();
            }
            @Override
            public void onFail(int code, String msg) {
                if (keyBoardBottomDialog!=null)
                keyBoardBottomDialog.showFail(msg);

                if(!paytype.equals(Constant.PAY_TYPE_BLANANCE)&&!paytype.equals(Constant.PAY_TYPE_BLANANCE))
                    ToastUtils.showToast( act,msg );
                prgessDialog.dismiss();
            }


        } );}

    }
}
